package com.zzyq.pc.web.report.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zzyq.pc.common.StandardDataFormat;
import com.zzyq.pc.common.base.BaseController;
import com.zzyq.pc.common.enums.RptView;
import com.zzyq.pc.common.enums.StarLevel;
import com.zzyq.pc.common.plugin.db.PageView;
import com.zzyq.pc.mongodb.dao.MongodbReport;
import com.zzyq.pc.mongodb.model.MongodbDate;
import com.zzyq.pc.utils.HttpUtils;
import com.zzyq.pc.utils.LoggerUtils;
import com.zzyq.pc.utils.WordUtils;
import com.zzyq.pc.web.report.model.Report;
import com.zzyq.pc.web.report.response.ModuleData;
import com.zzyq.pc.web.report.service.IDocExportor;
import com.zzyq.pc.web.report.service.IReportService;
import com.zzyq.pc.web.report.serviceImpl.PdfDocExportor;
import com.zzyq.pc.web.report.serviceImpl.WordDocExportor;

@Controller
@RequestMapping(value = "/report/", produces = "application/json;charset=UTF-8")
public class ReportController extends BaseController {

	MongodbReport mr = new MongodbReport();
	@Autowired
	private IReportService reportService;

	/**
	 * 报告列表查询
	 * 
	 * @param httpRequest
	 * @param response
	 * @param pageIndex
	 * @param pageSize
	 * @return List<Report> 对象集合
	 */
	@ResponseBody
	@RequestMapping("selectReport")
	public String selectReport(HttpServletRequest httpRequest, HttpServletResponse response, Integer pageIndex,
			Integer pageSize) {
		StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
		PageView pageView = null;
		try {
			// 初始值
			if (pageIndex == null || pageIndex <= 0) {
				pageIndex = 1;
			}
			if (pageSize == null || pageSize <= 0) {
				pageSize = 10;
			}
			pageView = new PageView(pageSize, pageIndex);
			List<Report> reports = reportService.selectByCompanyId(pageView);
			for (Report report : reports) {
				report.setReportName("每日报告");
			}
			format.setTotalPages(pageView.getPageCount());
			format.setTotalRecords(pageView.getRowCount());
			return HttpUtils.formatData(format, CODE_OK, MSG_OK, reports);
		} catch (Exception e) {
			e.printStackTrace();
			return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
		}
	}

	/**
	 * 报告预览
	 * 
	 * @param httpRequest
	 * @param response
	 * @param reportId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("selectOneReport")
	public String selectOneReport(HttpServletRequest httpRequest, HttpServletResponse response, Integer reportId) {
		StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
		Map<String, Object> reportDataMap = new HashMap<String, Object>();
		if (null == reportId) {
			LoggerUtils.debug(getClass(), "reportId为NULL");
			return HttpUtils.formatData(format, CODE_EXCEPTION, "reportId:NULL", null);
		}
		try {
			reportDataMap = reportService.selectOneReport(reportId);
			if (null == reportDataMap) {
				return HttpUtils.formatData(format, CODE_ERROR, "报告ID:" + reportId + "不存在", null);
			}
			return HttpUtils.formatData(format, CODE_OK, MSG_OK, reportDataMap);
		} catch (Exception e) {
			e.printStackTrace();
			return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
		}
	}

	/**
	 * 生成对应团体报告加入MySql数据库
	 * 
	 * @param httpRequest
	 * @param response
	 * @param companyId
	 *            团体ID
	 * @return
	 */
	@ResponseBody
	@RequestMapping("insertReport")
	public String insertReport(HttpServletRequest httpRequest, HttpServletResponse response, Integer companyId) {
		StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
		try {
			if (reportService.creatReport(companyId)) {
			return HttpUtils.formatData(format, CODE_OK, MSG_OK, null);
			}
			return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
		} catch (Exception e) {
			e.printStackTrace();
			return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
		}
	}

	/**
	 * 导出WORD 模板方式
	 * 
	 * @param httpRequest
	 * @param response
	 * @param reportId
	 *            报告ID
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "creatDox2")
	public String creatDox2(HttpServletRequest httpRequest, HttpServletResponse response, Integer reportId,
			@RequestParam(required = false) String svg) {
		StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
		if (null == reportId) {
			return HttpUtils.formatData(format, CODE_ERROR, MSG_ERROR_PARAMS, null);
		}
		// 设置字符集编码
		try {
			httpRequest.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e1) {
			log.error(e1.getMessage());
		}
		Map<String, Object> reportDataMap = new HashMap<String, Object>();
		List<MongodbDate> earlyWarningList = new ArrayList<MongodbDate>();// 预警舆情集合
		List<MongodbDate> HighRiskList = new ArrayList<MongodbDate>();// 高危舆情集合
		List<MongodbDate> negativeWarningList = new ArrayList<MongodbDate>();// 负面舆情集合
		List<Report> reportList = new ArrayList<Report>();// 报告对象集合
		List<String> imgs = new ArrayList<>();// 图片集合
		List<MongodbDate> list = null;
		list = reportService.getMongodbDate(reportId);
		// 环比数据
		Report thisreport = reportService.selectByPrimaryKey(reportId);// 本期环比数据
		reportList.add(thisreport);
		if (null != thisreport) {
			Report lastreport = reportService.selectReportByReportIdAndCompanyId(reportId, thisreport.getCompanyId(),
					thisreport.getReportTime());// 上期环比数据
			reportList.add(lastreport);
		} else {
			return HttpUtils.formatData(format, CODE_ERROR, "需导出报告ID：" + reportId + "不存在", null);
		}
		imgs.add(WordUtils.getImageStr(httpRequest.getServletContext().getRealPath("") + "/static/icons/star1.jpeg"));// 并不做卵事
		imgs.add(WordUtils.getImageStr(httpRequest.getServletContext().getRealPath("") + "/static/icons/star5.jpeg"));// 五星
		imgs.add(WordUtils.getImageStr(httpRequest.getServletContext().getRealPath("") + "/static/icons/star4.jpeg"));// 四星
		imgs.add(WordUtils.getImageStr(httpRequest.getServletContext().getRealPath("") + "/static/icons/star3.jpeg"));// 三星
		imgs.add(WordUtils.getImageStr(httpRequest.getServletContext().getRealPath("") + "/static/icons/star2.jpeg"));// 两星
		imgs.add(WordUtils.getImageStr(httpRequest.getServletContext().getRealPath("") + "/static/icons/star1.jpeg"));// 一星
		// // 查询三个集合数据
		// earlyWarningList =
		// reportService.getDataByStarLevel(StarLevel.limitlessStar.getIndex(),
		// StarLevel.FiveStar.getIndex(), reportId);
		// HighRiskList =
		// reportService.getDataByStarLevel(StarLevel.FiveStar.getIndex(),
		// StarLevel.ThreeStar.getIndex(),
		// reportId);
		// negativeWarningList =
		// reportService.getDataByStarLevel(StarLevel.ThreeStar.getIndex(),
		// StarLevel.OneStar.getIndex(), reportId);
		if (null != list && list.size() > 0 && !list.isEmpty()) {
			earlyWarningList = mr.warningEllipsis(list, StarLevel.limitlessStar.getIndex(),
					StarLevel.FiveStar.getIndex());
			HighRiskList = mr.warningEllipsis(list, StarLevel.FiveStar.getIndex(), StarLevel.ThreeStar.getIndex());
			negativeWarningList = mr.warningEllipsis(list, StarLevel.ThreeStar.getIndex(),
					StarLevel.OneStar.getIndex());
		}
		File file = null;
		InputStream fin = null;
		OutputStream out = null;
		String img2 = "";
		try {
			reportDataMap.put("earlyWarningList", WordUtils.ListFitter(earlyWarningList));
			reportDataMap.put("HighRiskList", WordUtils.ListFitter(HighRiskList));
			reportDataMap.put("negativeWarningList", WordUtils.ListFitter(negativeWarningList));
			reportDataMap.put("imgs", imgs);
			reportDataMap.put("count1", thisreport.getTotal());
			reportDataMap.put("count2", thisreport.getPositiveNum());
			reportDataMap.put("count3", thisreport.getNegativeNum());
			reportDataMap.put("count4", earlyWarningList.size());
			reportDataMap.put("count5", HighRiskList.size());
			reportDataMap.put("count6", negativeWarningList.size());
			reportDataMap.put("reportDay", thisreport.getReportName());
			reportDataMap.put("reportList", WordUtils.MomFitter(reportList));
			reportDataMap.put("img2", svg != null ? svg.replaceFirst("data:image/png;base64,", "") : img2);
			// file = WordUtils.createDoc(reportDataMap, "resume");
			file = WordUtils.createDoc2(reportDataMap, "test");
			fin = new FileInputStream(file);
			String name = "每日报告(" + thisreport.getReportName() + ")";
			// 设置字符集编码
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/msword");
			// 设置浏览器以下载方式处理该文件默认名为信息文章.doc
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String(name.getBytes("GBK"), "iso-8859-1") + ".doc");

			out = response.getOutputStream();
			byte[] buffer = new byte[1024 * 1024]; // 缓存区
			int bytesToRead = -1;
			// 通过循环将读入的word文件的内容输出到浏览器中
			while ((bytesToRead = fin.read(buffer)) != -1) {
				out.write(buffer, 0, bytesToRead);
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		} finally {
			if (fin != null)
				try {
					fin.close();
				} catch (IOException e) {
					log.error(e.getMessage());
				}
			if (out != null)
				try {
					out.close();
				} catch (IOException e) {
					log.error(e.getMessage());
				} // 关闭流
			if (file != null)
				file.delete(); // 删除临时文件
		}
		return HttpUtils.formatData(format, CODE_OK, MSG_OK, null);
	}

	/**
	 * 导出PDF报告
	 */
	@ResponseBody
	@RequestMapping(value = "exportPdf")
	public String exportPdf(HttpServletRequest request, HttpServletResponse response, Integer reportId,
			@RequestParam(required = false) String svg) {
		StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
		if (null == reportId) {
			return HttpUtils.formatData(format, CODE_ERROR, MSG_ERROR_PARAMS, null);
		}
		List<MongodbDate> list = null;
		// 文件名称
		String rptTitle = "每日日报";
		List<ModuleData> moduleDatas = new ArrayList<>();
		// 一些数据信息
		Map<String, String> infos = new HashMap<>();
		Map<String, String> svgs = new HashMap<String, String>();
		OutputStream out = null;
		try {
			if (StringUtils.isNotBlank(svg)) {
				// svgs = new ObjectMapper().readValue(svg, Map.class);
				svg = svg.replaceFirst("data:image/png;base64,", "").replaceFirst("data:image/jpeg;base64,", "");
				svgs.put("5", svg);
			}
			List<MongodbDate> earlyWarningList = new ArrayList<MongodbDate>();// 预警舆情集合
			List<MongodbDate> HighRiskList = new ArrayList<MongodbDate>();// 高危舆情集合
			List<MongodbDate> negativeWarningList = new ArrayList<MongodbDate>();// 负面舆情集合
			list = reportService.getMongodbDate(reportId);
			// 查询三个集合数据
			// earlyWarningList =
			// reportService.getDataByStarLevel(StarLevel.limitlessStar.getIndex(),
			// StarLevel.FiveStar.getIndex(), reportId);
			// HighRiskList =
			// reportService.getDataByStarLevel(StarLevel.FiveStar.getIndex(),
			// StarLevel.ThreeStar.getIndex(), reportId);
			// negativeWarningList =
			// reportService.getDataByStarLevel(StarLevel.ThreeStar.getIndex(),
			// StarLevel.OneStar.getIndex(), reportId);
			if (null != list && list.size() > 0 && !list.isEmpty()) {
				earlyWarningList = mr.warningEllipsis(list, StarLevel.limitlessStar.getIndex(),
						StarLevel.FiveStar.getIndex());
				HighRiskList = mr.warningEllipsis(list, StarLevel.FiveStar.getIndex(), StarLevel.ThreeStar.getIndex());
				negativeWarningList = mr.warningEllipsis(list, StarLevel.ThreeStar.getIndex(),
						StarLevel.OneStar.getIndex());
			}
			List<Report> reportList = new ArrayList<Report>();// 报告对象集合
			// 环比数据
			Report thisreport = reportService.selectByPrimaryKey(reportId);// 本期环比数据
			reportList.add(thisreport);
			if (null != thisreport) {
				Report lastreport = reportService.selectReportByReportIdAndCompanyId(reportId,
						thisreport.getCompanyId(), thisreport.getReportTime());// 上期环比数据
				reportList.add(lastreport);
			} else {
				return HttpUtils.formatData(format, CODE_ERROR, "需导出报告ID：" + reportId + "不存在", null);
			}
			String str = "(" + thisreport.getReportName() + ")";
			rptTitle = rptTitle + str;
			infos.put(IDocExportor.GAROUP_NAME, rptTitle);
			// infos.put(IDocExportor.RPT_NAME, str);
			for (RptView rptView : RptView.values()) {
				ModuleData moduleData = new ModuleData(rptView.getId(), rptView.getName(), rptView.getTitle(),
						rptView.getText(), rptView.getTypeId(), rptView.getExtra(), rptView.getPointX(),
						rptView.getPointY());
				try {
					reportService.analyzeDisplayData(moduleData, earlyWarningList, HighRiskList, negativeWarningList,
							reportList);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					continue;
				}
				moduleDatas.add(moduleData);
			}
			out = response.getOutputStream();
			response.reset();// 清空输出流
			response.setHeader("Content-disposition",
					"attachment; filename=" + new String(rptTitle.getBytes("gb2312"), "ISO8859-1") + ".pdf");// 设定输出文件头
			response.setContentType("application/octet-stream; charset=UTF-8");// 定义输出类型
			new PdfDocExportor().createDoc(infos, moduleDatas, svgs, out).writeToStream();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
		}
		return null;
	}

	/**
	 * 导出Word报告Apache_POI_3.8版
	 */
	@ResponseBody
	@RequestMapping(value = "creatDox")
	public String creatDox(HttpServletRequest request, HttpServletResponse response, Integer reportId,
			@RequestParam(required = false) String svg) {
		StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
		if (null == reportId) {
			return HttpUtils.formatData(format, CODE_ERROR, MSG_ERROR_PARAMS, null);
		}
		List<MongodbDate> list = null;
		// 文件名称
		String rptTitle = "每日日报";
		List<ModuleData> moduleDatas = new ArrayList<>();
		// 一些数据信息
		Map<String, String> infos = new HashMap<>();
		Map<String, String> svgs = new HashMap<String, String>();
		OutputStream out = null;
		try {
			if (StringUtils.isNotBlank(svg)) {
				// svgs = new ObjectMapper().readValue(svg, Map.class);
				svg = svg.replaceFirst("data:image/png;base64,", "").replaceFirst("data:image/jpeg;base64,", "");
				svgs.put("5", svg);
			}
			List<MongodbDate> earlyWarningList = new ArrayList<MongodbDate>();// 预警舆情集合
			List<MongodbDate> HighRiskList = new ArrayList<MongodbDate>();// 高危舆情集合
			List<MongodbDate> negativeWarningList = new ArrayList<MongodbDate>();// 负面舆情集合
			list = reportService.getMongodbDate(reportId);
			if (null != list && list.size() > 0 && !list.isEmpty()) {
				earlyWarningList = mr.warningEllipsis(list, StarLevel.limitlessStar.getIndex(),
						StarLevel.FiveStar.getIndex());
				HighRiskList = mr.warningEllipsis(list, StarLevel.FiveStar.getIndex(), StarLevel.ThreeStar.getIndex());
				negativeWarningList = mr.warningEllipsis(list, StarLevel.ThreeStar.getIndex(),
						StarLevel.OneStar.getIndex());
			}
			List<Report> reportList = new ArrayList<Report>();// 报告对象集合
			// 环比数据
			Report thisreport = reportService.selectByPrimaryKey(reportId);// 本期环比数据
			reportList.add(thisreport);
			if (null != thisreport) {
				Report lastreport = reportService.selectReportByReportIdAndCompanyId(reportId,
						thisreport.getCompanyId(), thisreport.getReportTime());// 上期环比数据
				reportList.add(lastreport);
			} else {
				return HttpUtils.formatData(format, CODE_ERROR, "需导出报告ID：" + reportId + "不存在", null);
			}
			String str = "(" + thisreport.getReportName() + ")";
			rptTitle = rptTitle + str;
			infos.put(IDocExportor.GAROUP_NAME, rptTitle);
			// infos.put(IDocExportor.RPT_NAME, str);
			for (RptView rptView : RptView.values()) {
				ModuleData moduleData = new ModuleData(rptView.getId(), rptView.getName(), rptView.getTitle(),
						rptView.getText(), rptView.getTypeId(), rptView.getExtra(), rptView.getPointX(),
						rptView.getPointY());
				try {
					reportService.analyzeDisplayData(moduleData, earlyWarningList, HighRiskList, negativeWarningList,
							reportList);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					continue;
				}
				moduleDatas.add(moduleData);
			}
			out = response.getOutputStream();
			response.reset();// 清空输出流
			response.setHeader("Content-disposition",
					"attachment; filename=" + new String(rptTitle.getBytes("gb2312"), "ISO8859-1") + ".doc");// 设定输出文件头
			response.setContentType("application/msword");// 定义输出类型
			new WordDocExportor().createDoc(infos, moduleDatas, svgs, out).writeToStream();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
		}
		return null;
	}
}
